<script lang="ts" setup>
import type {
  TextArea,
  TextAreaAppearance,
  TextAreaAutocomplete,
  TextAreaResize,
  TextAreaSize,
} from '@fluentui/web-components';

withDefaults(
  defineProps<{
    appearance?: TextAreaAppearance;
    autocomplete?: TextAreaAutocomplete;
    autoResize?: boolean;
    block?: boolean;
    disabled?: boolean;
    displayShadow?: boolean;
    maxlength?: number;
    minlength?: number;
    name?: string;
    placeholder?: string;
    readonly?: boolean;
    required?: boolean;
    resize?: TextAreaResize;
    size?: TextAreaSize;
    spellcheck?: boolean;
  }>(),
  {
    appearance: 'outline',
    autocomplete: undefined,
    autoResize: false,
    block: true,
    displayShadow: false,
    disabled: false,
    maxlength: undefined,
    minlength: undefined,
    name: undefined,
    placeholder: undefined,
    readonly: false,
    required: false,
    resize: 'none',
    size: undefined,
    spellcheck: false,
  },
);

const emit = defineEmits<{
  change: [event: Event];
  input: [event: Event];
  select: [event: Event];
}>();
const value = defineModel<string>({
  default: '',
});
// Handle events
const handleInput = (event: Event) => {
  const target = event.target as HTMLTextAreaElement;
  emit('input', event);
  // Update the model directly
  value.value = target.value;
};

const handleChange = (event: Event) => {
  const target = event.target as HTMLTextAreaElement;
  emit('change', event);
  // Also update the model on change
  value.value = target.value;
};

const handleSelect = (event: Event) => {
  emit('select', event);
};

const textArea = ref<TextArea>();

onMounted(() => {
  nextTick(() => {
    if (textArea.value) {
      textArea.value.value = value.value;
    }
  });
});
</script>

<template>
  <fluent-textarea
    ref="textArea"
    :appearance="appearance"
    :autocomplete="autocomplete"
    :auto-resize="autoResize"
    :block="block"
    :display-shadow="displayShadow"
    :disabled="disabled"
    :maxlength="maxlength"
    :minlength="minlength"
    :name="name"
    :placeholder="placeholder"
    :readonly="readonly"
    :required="required"
    :resize="resize"
    :size="size"
    :spellcheck="spellcheck"
    :value="value"
    @input="handleInput"
    @change="handleChange"
    @select="handleSelect"
  >
    <slot></slot>
  </fluent-textarea>
</template>

<style scoped></style>
